import SwiftUI

struct SettingsView: View {
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var appState: AppState
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 20) {
                    // 用户信息卡片
                    VStack {
                        HStack {
                            HStack {
                                // 头像
                                if let avatarUrl = appState.userInfo?.avatar, !avatarUrl.isEmpty {
                                    AsyncImage(url: URL(string: avatarUrl)) { phase in
                                        switch phase {
                                        case .success(let image):
                                            image
                                                .resizable()
                                                .aspectRatio(contentMode: .fill)
                                                .frame(width: 40, height: 40)
                                                .clipShape(Circle())
                                        default:
                                            Image(systemName: "person.circle.fill")
                                                .resizable()
                                                .frame(width: 40, height: 40)
                                                .clipShape(Circle())
                                        }
                                    }
                                    .frame(width: 40, height: 40)
                                    .padding(.trailing, 10)
                                } else {
                                    Image(systemName: "person.circle.fill")
                                        .resizable()
                                        .frame(width: 40, height: 40)
                                        .clipShape(Circle())
                                        .padding(.trailing, 10)
                                }
                                
                                // 用户名
                                Text(appState.userInfo?.nickname ?? "未登录")
                                    .font(.headline)
                            }
                            
                            Spacer()
                            
                            // 个人信息按钮
                            Button(action: {
                                // 跳转到个人信息页面
                            }) {
                                HStack {
                                    Text("个人信息")
                                        .foregroundColor(.gray)
                                    Image(systemName: "chevron.right")
                                        .foregroundColor(.gray)
                                }
                            }
                        }
                        .padding()
                        .background(Color(UIColor.systemBackground))
                        .cornerRadius(10)
                        .shadow(radius: 1)
                    }
                    .padding(.horizontal)
                    
                    // 设置列表
                    VStack(spacing: 0) {
                        // ID号
                        SettingRow(title: "ID号", content: appState.userInfo?.id.map { String($0) } ?? "", isLocked: true)
                        
                        // 手机号码
                        NavigationLink(destination: PhoneSettingView()) {
                            SettingRow(title: "手机号码", content: appState.userInfo?.phone ?? "", showArrow: true)
                        }
                        
                        // 密码
                        if let _ = appState.userInfo?.phone {
                            NavigationLink(destination: PasswordEditView()) {
                                SettingRow(title: "密码", content: "点击修改密码", showArrow: true)
                            }
                        }
                        
                        // 地址管理
                        NavigationLink(destination: AddressListView()) {
                            SettingRow(title: "地址管理", content: "立即设置", showArrow: true)
                        }
                        
                        // 资质证明
                        NavigationLink(destination: AgreementView(title: "资质证明", type: "intelligentinfo")) {
                            SettingRow(title: "资质证明", content: "点击查看", showArrow: true)
                        }
                        
                        // 协议规则
                        NavigationLink(destination: AgreementView(title: "协议规则", type: "rules")) {
                            SettingRow(title: "协议规则", content: "点击查看", showArrow: true)
                        }
                        
                        // 账号注销
                        Button(action: {
                            // 跳转到账号注销页面
                        }) {
                            SettingRow(title: "账号注销", content: "注销后无法恢复", showArrow: true)
                        }
                    }
                    .background(Color(UIColor.systemBackground))
                    .cornerRadius(10)
                    .shadow(radius: 1)
                    .padding(.horizontal)
                    
                    // 退出登录按钮
                    if appState.isLoggedIn {
                        Button(action: {
                            // 显示退出登录确认
                            showLogoutConfirmation()
                        }) {
                            Text("退出登录")
                                .foregroundColor(.red)
                                .frame(maxWidth: .infinity)
                                .padding()
                                .background(Color(UIColor.systemBackground))
                                .cornerRadius(22.5)
                        }
                        .padding(.horizontal)
                    }
                }
                .padding(.vertical)
            }
            .navigationBarTitle("设置", displayMode: .inline)
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: {
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        Image(systemName: "chevron.left")
                            .foregroundColor(.primary)
                    }
                }
            }
        }
    }
    
    // 显示退出登录确认对话框
    func showLogoutConfirmation() {
        let alert = UIAlertController(title: "提示", message: "确认退出登录?", preferredStyle: .alert)
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "确认", style: .destructive) { _ in
            appState.logout()
            presentationMode.wrappedValue.dismiss()
        })
        
        // 获取当前的UIViewController
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
           let rootViewController = windowScene.windows.first?.rootViewController {
            var currentController = rootViewController
            while let presentedController = currentController.presentedViewController {
                currentController = presentedController
            }
            currentController.present(alert, animated: true)
        }
    }
}

// 设置行组件
struct SettingRow: View {
    var title: String
    var content: String
    var showArrow: Bool = false
    var isLocked: Bool = false
    
    var body: some View {
        HStack {
            Text(title)
                .foregroundColor(.primary)
            
            Spacer()
            
            HStack {
                Text(content)
                    .foregroundColor(.gray)
                
                if isLocked {
                    Image(systemName: "lock.fill")
                        .foregroundColor(.gray)
                        .font(.system(size: 14))
                }
                
                if showArrow {
                    Image(systemName: "chevron.right")
                        .foregroundColor(.gray)
                        .font(.system(size: 14))
                }
            }
        }
        .padding()
        .background(Color(UIColor.systemBackground))
        .overlay(
            Rectangle()
                .frame(height: 0.5)
                .foregroundColor(Color(UIColor.systemGray5))
                .padding(.leading),
            alignment: .bottom
        )
    }
}

// 占位视图，实际项目中需要实现这些页面
struct PhoneSettingView: View {
    var body: some View {
        Text("手机号码设置")
    }
}

struct PasswordEditView: View {
    var body: some View {
        Text("密码修改")
    }
}

struct AddressListView: View {
    var body: some View {
        Text("地址管理")
    }
}

struct AgreementView: View {
    var title: String
    var type: String
    
    var body: some View {
        Text("\(title) - \(type)")
    }
}

struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        SettingsView()
            .environmentObject(AppState())
    }
}